<?php

namespace App\Controller;

use app\BaseController;

class Admin extends BaseController
{
    public function __construct(\think\App $app)
    {
        $this->app = $app;
        $this->request = $this->app->request;

        $this->UserModel = new \app\common\model\User;
        $this->RankModel = new \app\common\model\Rank;
        $this->FilesModel = new \app\common\model\Files;
        $this->ProjectModel = new \app\common\model\Project;
        $this->RelevanceModel = new \app\common\model\Relevance;
    }

    // 超管修改账号
    public function userupdate()
    {
        if ($this->request->isPost()) {
            $superid = $this->request->param('superid', 0, 'trim');
            $userid = $this->request->param('userid', 0, 'trim');
            $username = $this->request->param('username', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $staffname = $this->request->param('staffname', '', 'trim');
            $rankid = $this->request->param('rankid', 0, 'trim');

            // 检查是否为超级管理员
            if ($superid <= 0) {
                return json(error_ful('超级管理员ID无效'));
            }
            $rankId = $this->UserModel->where('id', $superid)->value('rankid');
            $rankInfo = $this->RankModel->where('id', $rankId)->find();
            if (empty($rankInfo)) {
                return json(error_ful('超级管理员身份等级不存在'));
            }
            if ($rankInfo['weigh'] !== '99') {
                return json(error_ful('您的账号无此权限'));
            }

            // 检查修改的账号是否存在
            if ($userid <= 0) {
                return json(error_ful('未发现账号'));
            }
            $userInfo = $this->UserModel->where('id', $userid)->find();
            if (empty($userInfo)) {
                return json(error_ful('未发现账号'));
            }

            $data = [

            ];

            // 判断身份等级
            if (!empty($rankid)) {
                $rankInfo = $this->RankModel->where('id', $rankid)->find();

                // 查看是否修改超管自己
                if ($superid == $userid && $rankInfo['weigh'] !== '99') {
                    return json(error_ful('超级管理员账号有且只能有一个'));
                }
                if (empty($rankInfo)) {
                    return json(error_ful('身份等级不存在'));
                }
                if ($rankInfo['weigh'] === '99') {
                    return json(error_ful('超级管理员账号有且只能有一个'));
                }
                $data['rankid'] = $rankid;
            }

            $originalUsername = $userInfo['username']; // 原用户名
            $originalStaffname = $userInfo['staffname'];
            if (!empty($username) && $username !== $originalUsername) {
                $userOther = $this->UserModel
                    ->where('id', '<>', $userid)
                    ->where('username', '=', $username)
                    ->find();

                if (!empty($userOther)) {
                    return json(error_ful('账号重复'));
                }
                $data['username'] = $username;
            }

            if (!empty($password)) {
                // 生成密码盐
                $salt = bin2hex(random_bytes(16));  // 生成32位随机salt 
                $password = md5($salt . $password);
                $data['password'] = $password;
                $data['salt'] = $salt;
            }

            // 员工姓名不为空
            if (!empty($staffname) && $staffname !== $originalStaffname) {
                $data['staffname'] = $staffname;
            }

            $status = $this->UserModel->where('id', $userid)->update($data);

            if ($status === false) {
                return json(error_ful('修改失败,数据库错误'));
            } elseif ($status == 0) {
                return json(error_ful('没有修改任何信息'));
            } else {
                return json(success_ful('修改成功'));
            }

        }
    }

    // 超管删除账号
    public function userdelete()
    {
        if ($this->request->isPost()) {
            $superid = $this->request->param('superid', 0, 'trim');
            $userid = $this->request->param('userid', 0, 'trim');

            // 检查目标账号
            $userInfo = $this->UserModel->where('id', $userid)->find();
            if (empty($userInfo)) {
                return json(error_ful('账号不存在'));
            }
            $superWeigh = $this->RankModel->where('id', $userInfo['rankid'])->value('weigh');
            if ($superWeigh == '99') {
                return json(error_ful('超管账号禁止删除'));
            }

            // 检查操作账号权限
            $superInfo = $this->UserModel->where('id', $superid)->find();
            if (empty($userInfo)) {
                return json(error_ful("您的账号无权限"));
            }
            $weigh = $this->RankModel->where('id', $superInfo['rankid'])->value('weigh');
            if ($weigh !== '99') {
                return json(error_ful("您的账号无权限"));
            }

            $status = $this->UserModel->where('id', $userid)->delete();
            if ($status === false) {
                return json(error_ful("删除失败"));
            } elseif ($status == 0) {
                return json(error_ful("删除失败"));
            } else {
                return json(success_ful("删除成功"));
            }
        }

    }

    // 获取文件、文件夹数量
    public function countStatistics()
    {
        if ($this->request->isPost()) {
            $token = $this->request->param('token', '', 'trim');

            if (empty($token)) {
                return json(error_ful('账号权限不足'));
            }

            $publicProject = $this->ProjectModel->where(['deletetime' => null, 'protocol' => 'public'])->count();
            $protectedProject = $this->ProjectModel->where(['deletetime' => null, 'protocol' => 'protected'])->count();
            $filesNum = $this->FilesModel->where(['deletetime' => null])->count();

            $data = [
                'public_project' => $publicProject,
                'protected_project' => $protectedProject,
                'files_num' => $filesNum
            ];
            return json(success_ful('数量统计', $data));
        }
    }

    // 获取最近七天上传文件数量
    public function latest7day()
    {
        if ($this->request->isPost()) {
            // $token = $this->request->param('token', '', 'trim');

            // if(empty($token)){
            //     return json(error_ful('账号权限不足'));
            // }

            $endTime = time();  //现在时间
            $startTime = $endTime - 24 * 60 * 60;  //过去一天

            $latest7day = [];
            for ($i = 1; $i <= 7; $i++) {
                $startTime = $startTime - $i * (24 * 60 * 60);
                $endTime = $endTime - ($i - 1) * (24 * 60 * 60);

                $count = $this->FilesModel
                    ->where('createtime', '>', $startTime)
                    ->where('createtime', '<', $endTime)
                    ->count();

                $latest7day[] = $count;
            }

            return json(success_ful('过去七天上传文件数量', $latest7day));
        }
    }

    // 文件分组统计
    public function filesgroup()
    {
        if ($this->request->isPost()) {
            $token = $this->request->param('token', '', 'trim');

            if (empty($token)) {
                return json(error_ful('账号权限不足'));
            }

            $data = [];
            $groupList = $this->FilesModel->field('suffix')->group('suffix')->select();

            foreach ($groupList as $group) {
                $data[$group['suffix']] = $this->FilesModel->where('suffix', $group['suffix'])->count();
            }

            return json(success_ful('文件分组统计', $data));
        }
    }

}